<div class="full-screen">
    <!--2017.5.24 by qingfeng
    <header>
    <div class="a-bar">
        <a href="javascript:history.back()" class="a-back">
            <i class="arr left"></i>
            返回
        </a>
        <div class="a-name">
            购物车
        </div>
    </div>
    </header>-->
    <div class="full-padding"  id="cart_main">
        <div class="cart-pt">
            <{if $is_empty}>
            <{include file="wap/cart/cart_empty.html" app=b2c}>
            <{else}>
            <!-- 购物车主体 -->
            <{include file="wap/cart/cart_main.html" app=b2c}>
            <{/if}>
        </div>
    </div>
   
</div>
<script>
(function(){
   // $(window).scroll(function(e){
        //if($(this).scrollTop() > 95){
            //$('#J_total').addClass('fixed');
        //}else{
           // $('#J_total').removeClass('fixed');
        //}
    //});
    $('.J-pre').bind('click',function(e){
        $(this).toggleClass('act');
        $(this).parents('.pt-h-item').find('.pre-info').toggleClass('hide');
    });

    $('#order_promotion .d-line').bind('click',function(){
        $('#J_pre_info').toggleClass('hide');
        $(this).find('.pre-list').toggleClass('hide');
    });

    // 设置商品数量
    function setQuantity(el,flag){
        var ipt = el.parent().find('.num-ipt'),
            max = parseInt(el.parents('.pt-h-item').find('.max-num').val()),
            min = parseInt(el.parents('.pt-h-item').find('.min-num').val()),
            val = ipt.val();

        switch(flag){
            case 1:
                if(!/^\d+$/.test(val)) 
                    ipt.val(min);
                else if(val > min)
                    ipt.val( val-1 );
                else if(val == min)
                    popup('此商品最少购买' + min + '件');
                break;
            case 2:
                if(val < max)
                    ipt.val( +val+1 );
                else if(val == max)
                    popup('此商品最多只能购买' + max + '件');
                break;
            case 3:
                if(!/^\d+$/.test(val)) {
                    ipt.val(min);
                } else if(val > max){
                    popup('此商品最多只能购买' + max + '件');
                    ipt.val(max);
                } else if(val < min){
                    popup('此商品最少购买' + min + '件');
                    ipt.val(min);
                }
                break;
        }
        function popup(msg) {
            var tpl = $('<div class="popup">' + msg + '</div>').appendTo(document.body);
            var timer = setTimeout(function(){
                tpl.remove();
            }, 3000);
        }

        var data = $('<form action=""></form>').append(el.parents('.pt-h-item').clone()).serialize();
        $.post('<{link app=b2c ctl=wap_cart act=update}>',data+"&response_type=true",function(re){
            var o = JSON.parse(re),
                promotion = $('#order_promotion .content'),
                unuse_rule = $('#unused_promotion .content'),
                ul = '';
            if(o.promotion){
                if(o.promotion.order){
                    $.each(o.promotion.order,function(){
                        ul += '<li><b class="f-red">['+this.desc_tag+']</b>'+this.name+'</li>';
                    });
                    promotion.html(ul);
                    ul = '';
                }else{
                    promotion.html('');
                }
            }else{
                promotion.html('');
            }
            if(o.unuse_rule){
                $.each(o.unuse_rule,function(){
                    ul += '<li><b class="f-red">['+this.desc_tag+']</b>'+this.name+'</li>';
                unuse_rule.html(ul);
                });
            }else{
                unuse_rule.html('');
            }

            el.parents('.pt-h-item').find('.price').html(o.edit_ajax_data.buy_price);
            $('#J_total .price').html(o.sub_total.promotion_subtotal);
            $('#J_total .num').html(o.number.cart_number);
            $('#J_total').find('.checknum').text(toalnum());
        });

    }
    $('.J-pt-num').bind('click',function(e){
        var el = $(e.srcElement),
            n = 0;
        if( !el.hasClass('btn') )return;

        if( el.hasClass('minus') )n=1;
        if( el.hasClass('plus') )n=2;

        setQuantity(el,n);

    });
    $('.num-ipt').bind('change',function(){
        setQuantity( $(this),3 );
    });
    //仿confirm 开始 2016-7-31 qianjin
    $.MsgBox = {
        Alert: function (title, msg) {
          GenerateHtml("alert", title, msg);
          btnOk(); //alert只是弹出消息，因此没必要用到回调函数callback
          btnNo();
        },
        Confirm: function (title, msg ) {
          GenerateHtml("confirm", title, msg);
          btnOk();
          btnNo();
        }
    }
     
    //生成Html
    var GenerateHtml = function (type, title, msg) {

    var _html = "";

    _html += '<div id="mb_box"></div><div id="mb_con"><span id="mb_tit">' + title + '</span>';
    // html += '<a id="mb_ico">x</a><div id="mb_msg">' + msg + '</div><div id="mb_btnbox">';
    _html += '<div id="mb_msg">' + msg + '</div><div id="mb_btnbox">';

    if (type == "alert") {
      _html += '<input id="mb_btn_ok" type="button" value="确定" />';
    }
    if (type == "confirm") {
      _html += '<input id="mb_btn_ok" type="button" value="确定" />';
      _html += '<input id="mb_btn_no" type="button" value="取消" />';
    }
    _html += '</div></div>';

    //必须先将_html添加到body，再设置Css样式
    $("body").append(_html); GenerateCss();
    }
     
    //生成Css
    var GenerateCss = function () {

    $("#mb_box").css({ width: '100%', height: '100%', zIndex: '99999', position: 'fixed',
      filter: 'Alpha(opacity=60)', backgroundColor: 'black', top: '0', left: '0', opacity: '0.6'
    });

    $("#mb_con").css({ zIndex: '999999', width: '250px', position: 'fixed',
      backgroundColor: 'White', borderRadius: '15px', top: '50%', left: '20%'
    });

    $("#mb_tit").css({ display: 'block', fontSize: '14px', color: '#444', padding: '10px 15px',
      backgroundColor: '#DDD', borderRadius: '15px 15px 0 0',
      borderBottom: '3px solid #FF555A', fontWeight: 'bold'
    });

    $("#mb_msg").css({ padding: '20px', lineHeight: '20px',
      borderBottom: '1px dashed #DDD', fontSize: '13px'
    });

    //$("#mb_ico").css({ display: 'block', position: 'absolute', right: '10px', top: '9px',
    //  border: '1px solid Gray', width: '18px', height: '18px', textAlign: 'center',
    //  lineHeight: '16px', cursor: 'pointer', borderRadius: '12px', fontFamily: '微软雅黑'
    //});

    $("#mb_btnbox").css({ margin: '15px 0 10px 0', textAlign: 'center' });
    $("#mb_btn_ok,#mb_btn_no").css({ width: '85px', height: '30px', color: 'white', border: 'none' });
    $("#mb_btn_ok").css({ backgroundColor: '#FF555A' });
    $("#mb_btn_no").css({ backgroundColor: 'gray', marginLeft: '20px' });


    //右上角关闭按钮hover样式
    //$("#mb_ico").hover(function () {
    //  $(this).css({ backgroundColor: 'Red', color: 'White' });
    //}, function () {
     // $(this).css({ backgroundColor: '#DDD', color: 'black' });
    //});

    var _widht = document.documentElement.clientWidth; //屏幕宽
    var _height = document.documentElement.clientHeight; //屏幕高

    var boxWidth = $("#mb_con").width();
    var boxHeight = $("#mb_con").height();

    //让提示框居中
    // $("#mb_con").css({ top: (_height - boxHeight) / 2 + "px", left: (_widht - boxWidth) / 2 + "px" });
    }
          
      //确定按钮事件
    var btnOk = function () {
    $("#mb_btn_ok").click(function (e) {
        $("#mb_box,#mb_con").remove();
        var oo = $(e.target);
        var data = $('<form action=""></form>').append(Remove.parents('.pt-h-item').clone()).serialize();
        $.post('<{link app=b2c ctl=wap_cart act=remove}>',data+"&response_type=true",function(re){
            //2017-5-27购物车删除优化 by maming
            var rs = JSON.parse(re);
            if(rs.is_empty){
                window.location.reload();
            } else {
                Remove.parents('.pt-h-item').remove();
                $('#J_total .price').html(rs.sub_total.promotion_subtotal);
                $('#J_total .num').html(rs.number.cart_number);    
            }


            // alert(re);
            // var rs = JSON.parse(re);
            // if(rs.is_empty) return location.reload();
            // $('#J_total .price').html(rs.sub_total.promotion_subtotal);
            // $('#J_total .num').html(rs.number.cart_number);
            // if(rs.error) return alert(rs.error);
            // oo.parents('.pt-h-item').remove();
            // if(p.hasClass('item') && $('.pt-list').children().length == 2){
            //     oo.parents('.pt-h-item').remove();
            //     $('cart-pt').remove();
            // }else{
            //     p.destroy();
            // }
        });
        //刷新网页
        // window.location.reload();
    });
    }
     
    //取消按钮事件
    var btnNo = function () {
    $("#mb_btn_no,#mb_ico").click(function () {
      $("#mb_box,#mb_con").remove();
    });
    }
    //仿confirm结束
    //注册全局变量，保存，点击后的，商品信息 2016-7-21
    window.Remove;
    // 移除商品
    $('.J-remove').bind('click',function(e){
        window.Remove = $(this);
        $.MsgBox.Confirm("金邻速购提示您","确认删除该产品吗？");
    });

    // 初始化购物车的收藏按钮状态
    var favmid = $.fn.cookie('S[MEMBER]');
    var gfav = $.fn.cookie("S[GFAV]["+favmid+"]");
    var gfav = decodeURIComponent(gfav);
    $('.favlist').each(function(index){
        if( gfav.split(',').indexOf( $(this).attr('data-gid') ) > -1 )
        {
            $(this).removeClass('btn-addfav').addClass('btn-faved').html('已收藏');
        }else{
            $(this).removeClass('btn-faved').addClass('btn-addfav').html('收藏');
        }
    });

    //收藏商品
    $('.btn-addfav').bind('click',function(){
        var $this = $(this);
        if($this.hasClass('btn-faved')) return;
        var data = 'gid='+$this.attr('data-gid')+'&type=goods';
        $.post('<{link app=b2c ctl=wap_member act=ajax_fav}>',data,function(re){
            //var re = $.parseJSON(re);
            //if(re.success){
                //$this.hide().next().show();
                $this.removeClass('btn-addfav').addClass('btn-faved').html('已收藏');
            //}
        });
        return false;
    });

    // 购物车结算
    $('.J_settlement').bind('click',function(e){
        //改写了方法：购物车生成订单之前，新增“商品数量是否超过最大可销售数”的二次判断 qianjin 2016-7-11
        var max = $('.max-num');
        var num = $('.num-ipt');
        var goods = $('.pt-h-name');
        var count = 0;
        for (var i = max.length - 1; i >= 0; i--) {
            //将字符串转成整型，不然比较会出错 qianjin 2016-7-13
            if(parseFloat(num[i].value) > parseFloat(max[i].value)){
                count++;
                alert('商品:'+goods[i].innerText+'最多购买' + max[i].value + '件');
            }
        };
        if(count == 0){
	    //2017-4-2 by jeff,购物车列表创建的form必须加入到body中后才能提交
            var form =$('<form>').attr({
                'action':'<{link app=b2c ctl=wap_cart act=checkout}>',
                'method':'post'
            }).append($('.pt-list').clone());//submit();
	    $(document.body).append(form.hide());
	    form.submit();
            return false;
        }else{
            return true;
        }
    });


     //全选或多选处理  add by qingfeng 2017-5-10     end    
    var CheckAll = $('#items_check_all'),Checks = $('#cart_main').find("input[name^='check']");
    var removeUrl = '<{link app=b2c ctl=wap_cart act=remove}>';
    var cls = Checks.length;



    
    //全选或多选处理 add  by qingfeng 2017-5-10
    if (cls > 0) {
    
        //判断是否全部被选中函数
        function isAllChecked() {       
            for(var i = 0; i < cls;i ++) {
                if(!Checks[i].checked) return false;
            }
            return true;
        }
        
       //统计购物车中已选择的商品数量
        function toalnum(){
            var num = 0;
            Checks.each(function(index,item){
                if(item.checked){
                    var itemnum = parseInt($(item).parents('.pt-h-item').find('.num-ipt').prop('value'));
                    num = num + itemnum;
                }       
            })
            return num;
        }

        //给选中的商品item加上状态函数
        function itemChecked (el){
            var item = $(el);
            item.parents('.pt-h-item').toggleClass('active').css('background',el.checked ? '#efefef':'#fff');
            updateGoodsMark(item);
        }

        //先执行一次判断，如果所有的商品都被选择，全选按钮设置为选中状态
        CheckAll.prop('checked',isAllChecked());

        //执行购物车数量统计函数，更改已选择数量
        $('#J_total').find('.checknum').text(toalnum());
        
        $('#cart_main').on('click', function(e){
            var target = e.target;
            if(target.tagName.toLowerCase() == 'input' && target.type == 'checkbox'){
            
                //判断点中的是全选还是item
                //这里一般可以加一些特殊的标识，比如说className,name等等
                if(target.name == 'allcheck'){
                    Checks.each(function(index,item){
                        var checked = item.checked = CheckAll.prop('checked');
                        itemChecked(item);
                    });
                }else{
                    CheckAll.prop('checked',isAllChecked());
                    itemChecked(target);
                }

                //变更已选择商品数量
                $('#J_total').find('.checknum').text(toalnum());
                
            }
        })
    }
    //全选或多选处理  add by qingfeng 2017-5-10     end
    

    //add by qingfeng 2017-5-11 批量删除    
    $('.action-delete').on('click',function(e){
        //e.preventDefault();
        if(!confirm('您确认要批量删除所选商品？')) return false;
        
        //用数组存放参数组      
        var data = [];
        Checks.each(function(index,item){
            if(item.checked){
                var thisParent = $(this).parents('.pt-h-item');
                data.push($('<form action=""></form>').append(thisParent.clone()).serialize()+'&response_type=true');
                thisParent.remove();                
            }
        });
        var strdata = data.join(',');
        //alert(data);return;
        
        //一次性提交
        $.post(removeUrl,strdata,function(re){
            rs = JSON.parse(re); //但返回的json数据有错误            
            console.log(rs);
            if(rs.is_empty) return location.reload();
            $('#J_total .price').html(rs.sub_total.promotion_subtotal);
            $('#J_total .num').html(rs.number.cart_number);
            if(rs.error) return alert(rs.error);            
            window.location.href = window.location.href;
        });     
        return false;
    });
    
    
    //add by qingfeng 2017-5-11 清空购物车
  /*  $('.action-clean').bind('click',function(e){
        e.preventDefault();
        if(!confirm('您确认要清空购物车？')) return false;
        var data = 'obj_type=all&response_json=true';       
        $.post(removeUrl,data,function(re){
            window.location.href = window.location.href;
        });
        return false;
    });*/

    // 2017-5-17 shui 批量收藏 
    var checkbox = $('input[name^="check"]');
    $('.action-collect').bind('click',function(e){
        e.preventDefault();
        checkbox.each(function(index,item){
            var gid =  $(item).parents('.pt-h-item').find('input[name=goods_id]').attr('value');
            var data = 'gid='+gid + '&type=goods';
            var fbtn = $(item).parents('.pt-h-item').find(".favlist");
            if(item.checked){
                $.post('<{link app=b2c ctl=wap_member act=ajax_fav}>',data,function(re){
                fbtn.removeClass('btn-addfav').addClass('btn-faved').html('已收藏');
                });
            }
        });
        if($("input[type='checkbox']:checked").length > 0 ){
            alert('收藏成功')
        }else{
            alert('您还没有选中商品呢~~')

        }
            // return false;
    });
    //  end

       
    
    //更新商品价格
    function updateGoodsMark(el){
        var data = $('<form action=""></form>').append(el.parents('.pt-h-item').clone()).serialize();
         $.ajax({
            type:'POST',
            url:'<{link app=b2c ctl=wap_cart act=update}>',
            data: data+"&mark=1&response_type=true",
            //timeout:300,
            async:false,
            success: function(re){
                var o = JSON.parse(re),

                promotion = $('#order_promotion .content'),
                unuse_rule = $('#unused_promotion .content'),
                ul = '';
            if(o.promotion){
                if(o.promotion.order){
                    $.each(o.promotion.order,function(){
                        ul += '<li><b class="f-red">['+this.desc_tag+']</b>'+this.name+'</li>';
                        //if(!check_all_items)window.location.href=window.location.href;
                    });
                    promotion.html(ul);
                    ul = '';
                }else{
                    promotion.html('');
                }
            }else{
                promotion.html('');
                //if(!check_all_items)window.location.href=window.location.href;
            }
            if(o.unuse_rule){
                $.each(o.unuse_rule,function(){
                    ul += '<li><b class="f-red">['+this.desc_tag+']</b>'+this.name+'</li>';
                unuse_rule.html(ul);
                });
            }else{
                unuse_rule.html('');
            }

            //el.parents('.pt-h-item').find('.price').html(o.edit_ajax_data.buy_price);
            $('#J_total .price').html(o.sub_total.promotion_subtotal);
           $('#J_total .a-price').html(o.sub_total.discount_amount_order);
     //       $('#J_total .num').html(o.number.cart_number);              
            }
        })
    }

})();
</script>


